

package com.gc.server.service.impl;
import com.gc.server.dao.BusApplyDao;
import com.gc.server.dao.LevelDao;
import com.gc.server.dao.UserDao;
import com.gc.server.entity.*;
import com.gc.server.enums.BusApplyStatusEnum;
import com.gc.server.enums.LevelEnum;
import com.gc.server.service.UserService;
import com.gc.server.vo.ApplyUserVo;
import com.gc.server.vo.CostApplyVo;
import com.yf.response.RRException;
import lombok.SneakyThrows;
import org.springframework.transaction.annotation.Transactional;
import com.gc.server.vo.up.ApplyUp;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.excel.context.AnalysisContext;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import com.alibaba.excel.event.AnalysisEventListener;
import org.springframework.stereotype.Service;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import  com.gc.server.vo.down.ApplyDown;

import java.math.BigDecimal;
import java.net.URL;
import java.util.*;
import java.io.IOException;
import java.net.URLEncoder;
import com.gc.server.vo.down.ApplyDown;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;
import com.gc.server.dao.ApplyDao;
import com.gc.server.vo.ApplyVo;
import com.gc.server.service.ApplyService;
import com.yf.service.impl.BaseServiceImpl;

/**
 * 账户记录Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date ${datetime}
 */
@Service
public class ApplyServiceImpl extends BaseServiceImpl<ApplyEntity> implements ApplyService {

    private ApplyDao dao;


    @Autowired
    public void setDao(ApplyDao dao) {
        this.dao = dao;
        super.setBaseDao(dao);
    }




    @Override
    public List<ApplyVo> findVo(ApplyVo vo){
        return dao.findVo(vo);
    }

    @Override
    public ApplyVo getVo(Long id){
        return dao.getVo(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveVo(ApplyVo vo){
        return dao.save(vo.getEntity());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateVo(ApplyVo vo){
        return dao.update(vo.getEntity());
    }



    @Override
    public void downLoad(HttpServletResponse response, List<ApplyVo> list) {
        try {
            List<ApplyDown> datas = list.stream().map(item -> new ApplyDown(item)).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel" );
            response.setCharacterEncoding("utf-8" );
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8" );
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx" );
            EasyExcel.write(response.getOutputStream(), ApplyDown.class).sheet("模板" ).doWrite(datas);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    @Override
    public void upload(InputStream file) {
        EasyExcel.read(file, ApplyUp.class, new UploadDataListener()).sheet().doRead();
    }



    class UploadDataListener extends AnalysisEventListener<ApplyUp> {


        @Override
        @Transactional(rollbackFor = Exception.class)
        public void invoke(ApplyUp upVo, AnalysisContext analysisContext) {
            saveVo(upVo.toVo());
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        }

    }




    /**内部方法**/



    /**外部方法实现**/

    @Override
    public List<ApplyVo> findMyShopUserAndDate(Long topUserId, Long userId, Date startDate, Date endDate) {
        List<Long> userIds = new ArrayList<>();
        if(userId!=null){
            userIds.add(userId);
        }else {
            userIds = userService.findTeam(topUserId);
        }
        if(userIds.size()==0) return new ArrayList<>();
        return dao.findByUserIdsAndDate(userIds,startDate,endDate);
    }

    @Autowired
    private UserService userService;

    @Override
    public List<ApplyVo> findByUserAndDate(Long userId, Date startDate, Date endDate) {
        return dao.findByUserAndDate(userId,startDate,endDate);
    }


    @Autowired
    private UserDao userDao;

    @Autowired
    private LevelDao levelDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApplyEntity check(Long userId, Long id, Integer status, String remark) {
        ApplyEntity applyEntity = dao.get(id);
        if (!applyEntity.getStatus().equals(BusApplyStatusEnum.WAIT.getIndex())) {
            throw new RRException("请勿重复操作!");
        }
        applyEntity.setAdminId(userId);
        UserEntity userEntity = userDao.get(userId);
        applyEntity.setAdminName(userEntity.getName());
        applyEntity.setRemark(remark);
        //如果通过的话 一天及以上由上一级审批  1-3天需要两级 3天以上总监
        if (status.equals(BusApplyStatusEnum.PASS.getIndex())) {
            LevelEntity adminLevel = levelDao.findByUserId(userId);
            BigDecimal ondDay = new BigDecimal(9);
            BigDecimal threeDay = new BigDecimal(27);
            if(adminLevel.getId() == LevelEnum.MANAGER3.getIndex()||adminLevel.getId() == LevelEnum.MANAGER2.getIndex()||applyEntity.getHours().compareTo(ondDay)<=0){ // 只有一天的 总监直接通过
                applyEntity.setStatus(BusApplyStatusEnum.PASS.getIndex());
            }else { // 不是总监  且超过一天的
                if(applyEntity.getHours().compareTo(threeDay)<=0){
                    // 1-3天 必须两级
                    LevelEntity userLevel = levelDao.findByUserId(applyEntity.getUserId());
                    if(adminLevel.getLv() - userLevel.getLv()==2){ //必须有两级 通过
                        applyEntity.setStatus(BusApplyStatusEnum.PASS.getIndex());
                    }
                }
            }
        } else {
            applyEntity.setStatus(status);
        }
        update(applyEntity);
        //同步所有的状态
        List<BusApplyEntity> items = busApplyDao.findByAid(applyEntity.getId());
        items.forEach(item -> {
            item.setAdminId(applyEntity.getAdminId());
            item.setAdminName(applyEntity.getAdminName());
            item.setRemark(applyEntity.getRemark());
            item.setStatus(applyEntity.getStatus());
            busApplyDao.update(item);
        });
        return applyEntity;
    }

    @Autowired
    private BusApplyDao busApplyDao;

    @Override
    public Integer sumCheck(Long userId) {
        return dao.sumCheck(userId);
    }

 
}
